import axios from 'axios'
import type { AxiosInstance } from 'axios'
import type { HYRequestInterceptors, HYRequestConfig } from './type'

import { ElLoading } from 'element-plus'

const DEFAULT_LOADING = true

class HYRequest {
  instance: AxiosInstance
  interceptors?: HYRequestInterceptors
  showLoading?: boolean
  loadingInstance: any

  constructor(config: HYRequestConfig) {
    this.instance = axios.create(config)
    this.interceptors = config.interceptors
    this.showLoading = config.showLoading ?? DEFAULT_LOADING

    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    )
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    )

    this.instance.interceptors.request.use(
      (config) => {
        // console.log('所有实例都有的拦截器，请求成功1')
        if (this.showLoading) {
          this.loadingInstance = ElLoading.service({
            lock: true,
            text: 'Loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
        }
        return config
      },
      (err) => {
        // console.log('所有实例都有的拦截器，请求失败1')
        return err
      }
    )

    this.instance.interceptors.response.use(
      (res) => {
        // console.log('所有实例都有的拦截器，响应成功1')
        //移除loading
        if (this.showLoading) {
          this.loadingInstance.close()
        }
        const data = res.data
        this.showLoading = DEFAULT_LOADING
        if (data.returnCode === '-1001') {
          console.log('请求失败,错误信息')
        } else {
          return res.data
        }
      },
      (err) => {
        // console.log('所有实例都有的拦截器，响应失败1')
        //例子：判断不同的httpErrorCode显示不同的错误信息
        if (err.response.status === 404) {
          console.log('404错误')
        }
        this.showLoading = DEFAULT_LOADING
        return err
      }
    )
  }

  request<T = any>(config: HYRequestConfig): Promise<T> {
    if (config.interceptors?.requestInterceptor) {
      config = config.interceptors.requestInterceptor(config)
    }

    if (config.showLoading === false) {
      this.showLoading = config.showLoading
    }
    return this.instance.request(config)
  }

  get<T = any>(config: HYRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'GET' })
  }
  post<T = any>(config: HYRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'POST' })
  }
  delete<T = any>(config: HYRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'DELETE' })
  }
  patch<T = any>(config: HYRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'PATCH' })
  }
}

export default HYRequest
